package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R save(@RequestBody Category category){
        //接收参数
        log.info("category: {}",category);

        //新增菜品
        boolean b = categoryService.save(category);

        return b ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */

    @GetMapping("/page")
    public R page(@RequestParam Integer page , Integer pageSize){
        //接收参数
        log.info("page = {},pageSize = {}", page, pageSize);

        //构建分页条件
        IPage<Category> categoryPage = new Page<Category>(page, pageSize);

        //构建查询条件
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        //先按照sort排序 ， 然后再按照更新时间倒序排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        //分页查询
        categoryService.page(categoryPage,lqw);

        //响应数据
        return R.success(categoryPage);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam long id){
        //接收参数
        log.info("删除分类，id：{}",id);

        //执行删除
       /* boolean b = categoryService.removeById(id);*/
        categoryService.deleteById(id);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改信息分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        log.info("修改的分类信息为: {}",category);
        categoryService.updateById(category);
        return R.success("修改信息分类成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lqw);

        return R.success(list);
    }

}
